<template>
  <div class="lpdsf">
    <div class="dzz">
      <DonVites />
    </div>

    <div class="dl">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
        label-width="auto" class="demo-ruleForm">
        <el-form-item label="账号" prop="username">
          <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import DonVites from '@/components/DonVites.vue'
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from '@/utils/Reuqest'
import { useRoute, useRouter } from 'vue-router'

const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const route = useRoute()
const username = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    callback()
  }
}
const pwd = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  pwd: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: username, trigger: 'blur' }],
  pwd: [{ validator: pwd, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const res = await axios.post('/api/login', { ...ruleForm })
      console.log(res, '66666666666666666666六')

      if (res.data.code === 0) {
        sessionStorage.setItem('token', res.data.token)
        sessionStorage.setItem("users",JSON.stringify(res.data.users))
        router.push('/home')
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>
<style lang="scss" scoped>
.dl {
  width: 40%;
  height: 300px;
  border: 2.5px solid #cb0808;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding-right: 40px;
  box-sizing: border-box;
}
</style>
